package com.iemes.service.impl.work_plan;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.ShoporderStatusChangeHisoryFormMap;
import com.iemes.entity.UDefinedDataValueFormMap;
import com.iemes.entity.WorkCenterFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.work_plan.ShoporderMaintenanceService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

@Service
public class ShoporderMaintenanceServiceImpl implements ShoporderMaintenanceService {
	@Inject
	private BaseMapper baseMapper;
	
	@Inject
	private CommonService commonService;
	
	private Logger log = Logger.getLogger(this.getClass());

	@Override
	@Transactional
	public void saveShoporder(ShoporderFormMap shoporderFormMap,int shoporderStattusBeforeHangup) throws BusinessException {
		try {			
			String id = shoporderFormMap.getStr("id");
			String shoporderNo = shoporderFormMap.getStr("shoporder_no");
			
			if(StringUtils.isEmpty(shoporderNo)) {
				throw new BusinessException("工单编号不能为空，请输入！");
			}
			
			ShoporderFormMap shoporderFormMap2 = new ShoporderFormMap();
			shoporderFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			shoporderFormMap2.put("shoporder_no", shoporderNo);
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap2);

			// 如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(listShoporderFormMap)) {
				// 更新
				ShoporderFormMap shoporderFormMap3 = new ShoporderFormMap();
				shoporderFormMap3 = listShoporderFormMap.get(0);
				id = shoporderFormMap3.getStr("id");
				shoporderFormMap.set("id", id);

				String baseInfoUpdateMsg = "";
				int shoporderStatus = shoporderFormMap3.getInt("status");
				Object ObjectStatus = shoporderFormMap.get("status");
				int newStatus = Integer.valueOf(String.valueOf(ObjectStatus));
				// String shoporderBaseInfoUpdateErrmsg = "";
				// 工单状态调整
				String changeReason = shoporderFormMap.getStr("shoporder_status_change_reason");
				String statusChangeMsg = changeShoporderStatus(shoporderFormMap3, newStatus, changeReason,
						shoporderStattusBeforeHangup);
				if (!statusChangeMsg.contains("SUCCESS")) {
					throw new BusinessException(statusChangeMsg);
				}
				if (shoporderStatus == 0) {
					// 如果工单处于创建状态，则允许修改工单的基本休息
					if (!statusChangeMsg.contains("SUCCESS_UPDATED")) {
						// 此时只更新工单的基本信息，状态信息保留,否则此时再更新一次工单状态到新的状态
						shoporderFormMap.set("status", shoporderStatus);
					}
					shoporderFormMap.put("shoporder_issued_number",
							shoporderFormMap3.getInt("shoporder_issued_number"));
					baseMapper.editEntity(shoporderFormMap);

				} else {
					baseInfoUpdateMsg += "工单处于 " + commonService.getShoporderStatusStr(shoporderStatus)
							+ " 状态，不允许修改基本信息";
				}
				if (statusChangeMsg.contains("SUCCESS_UPDATED")) {
					baseInfoUpdateMsg = "";
				}
				shoporderFormMap.put("baseInfoUpdateMsg", baseInfoUpdateMsg);

				baseMapper.editEntity(shoporderFormMap);
			} else {
				// 新增
				id = UUIDUtils.getUUID();
				shoporderFormMap.set("id", id);
				shoporderFormMap.put("shoporder_issued_number", 0);
				shoporderFormMap.put("status", 0);
				baseMapper.addEntity(shoporderFormMap);
			}

			// 2.添加或更新自定义数据信息
			String dataValue = shoporderFormMap.getStr("udefined_data");
			commonService.saveUDefinedDataValueS(id, dataValue);		
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("工单保存失败！" + e.getMessage());
		}
	}
	
	@Transactional
	private String changeShoporderStatus(ShoporderFormMap oldShoporderFormMap, int newStatus,String changeReason,int shoporderStattusBeforeHangup) throws BusinessException {
		try {
			String returnMsg = "SUCCESS";
			int oldStatus = oldShoporderFormMap.getInt("status");
			if (oldStatus != newStatus) {
				/*工单状态：0、创建；1、已下达；2、生产中；3、已完成；4、关闭；5、挂起；6、删除
				0	允许到4,5
				1	允许到4,5
				2	允许到4,5
				3	不允许调整
				4	不允许调整
				5	允许恢复到挂起前的状态*/
				String shoporderId =  oldShoporderFormMap.getStr("id");
				boolean canChange = true;
				if (oldStatus == 0 || oldStatus == 1 || oldStatus == 2) {
					if(newStatus!=4&&newStatus!=5) {
						canChange = false; 
					}
				}else if(oldStatus == 3 || oldStatus == 4) {
					canChange = false; 
				}
				else if(oldStatus == 5) {
					if(shoporderStattusBeforeHangup >= -1) {
						if(newStatus!=shoporderStattusBeforeHangup) {
							canChange = false; 
						}
					}else {
						canChange = false; 
					}	
				}
				
				if(!canChange) {
					return "工单状态为" + commonService.getShoporderStatusStr(oldStatus) +",不能调整为" 
				                        + commonService.getShoporderStatusStr(newStatus) +"状态";
				}
				oldShoporderFormMap.set("status", newStatus);
				baseMapper.editEntity(oldShoporderFormMap);
				
				ShoporderStatusChangeHisoryFormMap shoporderStatusChangeHisoryFormMap = new ShoporderStatusChangeHisoryFormMap();
				shoporderStatusChangeHisoryFormMap.put("id", UUIDUtils.getUUID());
				shoporderStatusChangeHisoryFormMap.put("shoporder_id",shoporderId);
				shoporderStatusChangeHisoryFormMap.put("shoporder_status_before_change", oldStatus);
				shoporderStatusChangeHisoryFormMap.put("shoporder_status_after_change", newStatus);
				shoporderStatusChangeHisoryFormMap.put("shoporder_status_change_reason", changeReason);
				shoporderStatusChangeHisoryFormMap.put("shoporder_status_change_time", DateUtils.getStringDateTime());
				shoporderStatusChangeHisoryFormMap.put("shoporder_status_change_user", ShiroSecurityHelper.getCurrentUsername());
				shoporderStatusChangeHisoryFormMap.put("create_time", DateUtils.getStringDateTime());
				shoporderStatusChangeHisoryFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());

				baseMapper.addEntity(shoporderStatusChangeHisoryFormMap);
				
				returnMsg = "SUCCESS_UPDATED";
			}
			return returnMsg;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delShoporder(String shoporderId) throws BusinessException {
		try {
			// 删除前要卡控工单的状态,不能删除处于生产状态的工单
			ShoporderFormMap shoporderFormMap2 = new ShoporderFormMap();
			shoporderFormMap2.put("id", shoporderId);
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap2);

			if (ListUtils.isNotNull(listShoporderFormMap)) {
				shoporderFormMap2 = listShoporderFormMap.get(0);
				int shoporderStatus = shoporderFormMap2.getInt("status");
				if(shoporderStatus != 0) {
					throw new BusinessException("工单处于 " + commonService.getShoporderStatusStr(shoporderStatus) +" 状态，不允许删除！");
				}
			}
			// 1.删除工单表
			ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
			shoporderFormMap.put("id", shoporderId);
			baseMapper.deleteByNames(shoporderFormMap);

			// 2.删除自定义数据表
			UDefinedDataValueFormMap uDefinedDataValueFormMap = new UDefinedDataValueFormMap();
			uDefinedDataValueFormMap.put("data_type_detail_id", shoporderId);
			baseMapper.deleteByNames(uDefinedDataValueFormMap);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("工单删除失败！" + e.getMessage());
		}
	}

}
